<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.where.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="margin_bottom_8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" width="100" prop="name" />
      <el-table-column label="路径" align="center" width="100" prop="path" />
      <el-table-column label="监控点位" align="center" prop="cameraIds">
        <template slot-scope="scope">
          <div flex="main:center">
            <div v-for="(item,index) in scope.row.cameras" :key="item.id+''+index"><el-tag size="mini">{{ item.name }}</el-tag><i v-if="index !== scope.row.cameras.length-1" class="el-icon-right" /></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:post:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:post:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改路径对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" @close="resetCheckedPlaces">
      <template>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="名称" prop="name" required>
            <el-input v-model="form.name" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="路径" prop="path" required>
            <el-input v-model="form.path" placeholder="请输入路径" />
          </el-form-item>
          <el-form-item label="监控点位" prop="path" size="mini">
            <treeselect v-model="form.checkedGroupids" :multiple="true" class="margin_bottom_12" :options="deptOptions" :normalizer="normalizer" placeholder="请先选择分组" @input="handleSelect" />
            <div class="margin_bottom_12">
              <el-button v-for="camera in cameras" :key="camera.id" size="mini" @click="form.cameras.push(camera)">{{ (camera||{}).name }}</el-button>
            </div>
            <!-- <el-steps :space="200">
              <el-step v-for="(camera,index) in computedPlaces" :key="index" :title="(camera||{}).name" />
            </el-steps>
            <div v-if="!cameras.length" class="text_aaa">请选择分组或该分组下无监控点位</div> -->
            <el-divider />
            <div flex="main:left" style="flex-wrap: wrap;">
              <div v-for="(camera,index) in form.cameras" :key="index" class="margin_bottom_6"><el-tag closable @close="form.cameras.splice(index,1)">{{ (camera||{}).name }} </el-tag><i v-if="index !== form.cameras.length-1" class="el-icon-right" /></div>
            </div>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { queryList, getById, deleteById, addUpdateItem } from '@/api/setting/patrolpath'
import { queryListByIds } from '@/api/setting/camera'
import Treeselect from '@riophae/vue-treeselect'
import { queryListAll as queryListInGroup } from '@/api/setting/group'
export default {
  name: 'PathComponent',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      deptOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 路径表格数据
      postList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        where: {}
        // status: undefined
      },
      // 表单参数
      form: {
        cameras: [],
        checkedGroupids: []
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
        // path: [
        //   { required: true, message: '路径不能为空', trigger: 'blur' }
        // ],
        // postSort: [
        //   { required: true, message: '路径不能为空', trigger: 'blur' }
        // ]
      },
      dynamicTags: ['标签一', '标签二', '标签三'],
      cameras: []
    }
  },
  computed: {
    computedPlaces() {
      return this.form.cameras.map(id => this.cameras.find(item => item.id === id))
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    resetCheckedPlaces() {
      this.cameras = []
      this.form.cameras = []
    },
    handleSelect(node, id) {
      this.$nextTick(() => {
        if (this.form.checkedGroupids.length) {
          queryListByIds(this.form.checkedGroupids).then(res => {
            this.cameras = res.data
            this.form.cameras = this.form.cameras.filter(item => !!this.cameras.find(subItem => subItem.id === item.id))
          })
        } else {
          this.resetCheckedPlaces()
        }
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.groupname,
        children: node.children
      }
    },
    /** 查询路径列表 */
    /** 查询部门下拉树结构 */
    getTreeselect() {
      queryListInGroup().then(response => {
        this.deptOptions = this.handleTree(response.data, 'id', 'pid')
      })
    },
    handleData(arr) {
      // const result = []
      // let id = ''
      // arr.forEach((item, index) => {
      //   item.cameras = [{ name: item.name, id: item.cameraid, groupid: item.groupid }]
      //   if (id === item.id) {
      //     const found = result.find(subItem => subItem.id === id)
      //     found.cameras.push({ name: item.name, id: item.cameraid, groupid: item.groupid })
      //   } else {
      //     result.push(item)
      //     id = item.id
      //   }
      // })
      return arr
    },
    getList() {
      this.loading = true
      queryList(this.queryParams).then(response => {
        // const arr = response.rows.flat()
        // this.postList = this.handleData(arr)

        this.postList = response.data.map(item => {
          if (!item.cameraIndexNum) return item
          const arr = item.cameraIndexNum.split(',')
          item.cameras = arr.map(cameraid => {
            return item.cameras.find(subItem => subItem.id === parseInt(cameraid))
          })
          return item
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 路径状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        path: undefined,
        name: undefined,
        cameras: [],
        checkedGroupids: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.where = {}
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()
      this.open = true
      this.title = '添加路径'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      const id = row.id || this.ids
      getById(id).then(response => {
        // const obj = this.handleData(response.data)[0]
        // Object.assign(this.form, obj)
        // console.log(this.form)
        this.form = response.data
        const { cameras, cameraIndexNum } = response.data

        const arr = []

        if (cameraIndexNum) {
          const arr = cameraIndexNum.split(',')
          this.form.cameras = arr.map(cameraid => cameras.find(subItem => subItem.id === parseInt(cameraid)))
        }
        this.form.cameras.forEach(item => {
          arr.push(item.group.id)
        })
        this.form.checkedGroupids = [...new Set(arr)]
        this.handleSelect()
        this.open = true
        this.title = '修改路径'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const { cameras } = this.form
          const cameraIndexNum = cameras.map(item => item.id).join()
          const recameras = cameras.filter(function(element, index, self) {
            return self.findIndex(el => el.id === element.id) === index
          })
          addUpdateItem({ ...this.form, cameras: recameras, cameraIndexNum }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.form.id ? '修改成功' : '新增成功')
              this.open = false
              this.getList()
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除路径编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteById(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm('是否确认导出所有路径数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        // return exportPath(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {})
    }
  }
}
</script>
